<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view>
		<view class="text-area">
			金额：<input v-model="price" class="input" />元
		</view>
		<view class="text-area">
			<button @click="wxPay()">微信支付</button>
		</view>
	</view>
</template>

<script>
	import UrlConfig from '@/common/config.js'
	export default {
		data() {
			return {
				title: '',
				price: 1
			}
		},
		onLoad() {

		},
		methods: {
			wxPay() {
				let _self = this;
				uni.login({
					success: res => {
						//code值(5分钟失效)
						// console.info(res.code);
						uni.request({
							//改成自己的服务地址
							url: UrlConfig.url_config + '/wx/getOpenid/' + res.code,
							method: 'GET',
							header: {
								'content-type': 'application/x-www-form-urlencoded',
								'Cookie': uni.getStorageSync('Cookie')
							},
							success: (res) => {
								//这里就拿到openid了,不过一般都是直接在后端使用了,不需要拿到前端了,我就是为了做个演示。
								console.info(res);
								let openId = res.data;
								uni.request({
									url: UrlConfig.url_config + '/wx/pay',
									method: 'POST',
									header: {
										'content-type': 'application/x-www-form-urlencoded',
										'Cookie': uni.getStorageSync('Cookie')
									},
									data: {
										'price': _self.price * 100,
										'openId': openId
									},
									dataType: 'json',
									success: function(data) {
										// console.log(JSON.stringify(data.data))
										let paydata = data.data
										uni.requestPayment({
											provider: 'wxpay',
											timeStamp: paydata.timeStamp,
											nonceStr: paydata.nonceStr,
											package: paydata.package,
											signType: 'MD5',
											paySign: paydata.sign,
											success: function(res) {
												console.log('success:' +
													JSON.stringify(res)
													);
											},
											fail: function(err) {
												console.log('fail:' + JSON
													.stringify(err));
											}
										});
									}
								});
							}
						})
					}
				});
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.input {
		background-color: #C0C0C0;
		width: auto;
	}
</style>
